package com.zzyl.nursing.service.impl;

import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备Service业务层处理
 * 
 * @author gziqi
 * @date 2025-01-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;


    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDevice(Device device)
    {
        //更新数据库中的设备信息
        int result = deviceMapper.updateById(device);

        //更新IOT平台上的设备信息
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> deviceNicknameInfos =new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo deviceNicknameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        deviceNicknameInfo.setDeviceName(device.getDeviceName());
        deviceNicknameInfo.setNickname(device.getNickname());
        deviceNicknameInfo.setProductKey(device.getProductKey());
        deviceNicknameInfos.add(deviceNicknameInfo);
        request.setDeviceNicknameInfo(deviceNicknameInfos);
        BatchUpdateDeviceNicknameResponse response;
        try {
            response= client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!response.getBody().getSuccess()){
            throw new BaseException("更新设备失败");
        }
        return result;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //设置请求参数
        QueryProductListRequest request = new QueryProductListRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setPageSize(100);
        request.setCurrentPage(1);

        //调用第三方接口查询产品列表
        QueryProductListResponse response ;

        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("同步失败");
        }
        //判断 如果数据为空  则中断请求
        if(!response.getBody().success){
            throw new BaseException("同步失败");
        }

        //获取同步到的数据
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.getBody().getData().getList().getProductInfo();
        // 存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSONUtil.toJsonStr(productInfo));
    }

    /**
     * 查询产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        // 从redis中查询数据
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        // 如果数据为空，则返回一个空集合
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        // 解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //查询数据库根据设备名称判断设备名称是否重复
        Long count = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));


        //如果重复结束
        if(count>0){
            throw new BaseException("设备名称重复");
        }

        //没有重复  调用iot平台接口注册设备
        RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try {
             response = client.registerDevice(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!response.getBody().getSuccess()){
            throw new BaseException("设备注册失败");
        }

        //IOT平台注册设备成功 判断位置类型是否为0 如果为0 是随身设备  设置物理类型为-1
        if(deviceDto.getLocationType()==0){
            deviceDto.setPhysicalLocationType(-1);
        }

        //不全新增时返回的iotid到设备对象
        String iotId = response.getBody().getData().getIotId();
        //对象属性拷贝 获取一个封装好属性的设备对象
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //添加设备的iotid
        device.setIotId(iotId);
        //保存设备到数据库
        int result = 0;
        try {
            result = deviceMapper.insert(device);
            if(result==0){
                //没有保存成功
                //删除iot平台上的设备
                deleteIOTDevice(deviceDto,iotId);
                throw new BaseException("该来人/位置已绑定该产品,请重新选择");
            }
        } catch (BaseException e) {
            deleteIOTDevice(deviceDto,iotId);
            throw new BaseException("该来人/位置已绑定该产品,请重新选择");
        }
    }

    /**
     * 删除IOT平台上的数据
     * @param deviceDto
     * @param iotId
     */

    private void deleteIOTDevice(DeviceDto deviceDto, String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setProductKey(deviceDto.getProductKey());
        request.setIotId(iotId);
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 分别从数据库和IOT平台上查询设备详细信息
     *
     * @param deviceDto
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //从IOT平台查询数据
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotId(deviceDto.getIotId());
        request.setProductKey(deviceDto.getProductKey());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse response;
        try {
            response= client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!response.getBody().success){
            throw new BaseException("查询设备详情失败");
        }
        //将查询到的信息封装到DeviceVo中
        DeviceVo deviceVo = BeanUtil.toBean(response.getBody().getData(), DeviceVo.class);
        //从数据库查询数据
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));
        //将查询到的数据拷贝到DeviceVo中 合并两类数据
        BeanUtil.copyProperties(device,deviceVo);

        //返回DeviceVo
        return deviceVo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest  request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
         try {
             response = client.queryThingModelPublished(request);
         } catch (Exception e) {
             throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
         }
         if(!response.getBody().getSuccess()){
             throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
         }
         return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest  request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response ;
        try {
            response=client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!response.getBody().getSuccess()){
            throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
        }
        return AjaxResult.success( response.getBody().getData());
    }

    /**
     * 删除IOT平台设备和数据可中的数据
     *
     * @param device
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDevice(Device device) {
        //删除数据库中的数据
        deviceMapper.delete(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,device.getIotId()).eq(Device::getProductKey,device.getProductKey()));
        //删除iot平台中的数据
        DeleteDeviceRequest request =new DeleteDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotId(device.getIotId());
        request.setProductKey(device.getProductKey());
        DeleteDeviceResponse response;
        try {
             response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("删除IOT平台数据失败");
        }
        if(!response.getBody().getSuccess()){
            throw new BaseException("删除IOT平台数据失败");
        }


    }
}
